<template>
  <div class="avatar-upload">
    <div v-if="avatarUrl">
      <img :src="avatarUrl" alt="头像" class="avatar-preview" />
    </div>
    <div v-else>
      <p>更换头像</p>
    </div>
    <div class="controls">
      <input type="file" @change="onFileChange" />
      <button @click="uploadAvatar" :disabled="!selectedFile">上传</button>
      <button @click="downloadAvatar" :disabled="!avatarUrl">下载</button>
    </div>
  </div>
</template>

<script>
import { UploadAvatar } from '../../api/service.js';

export default {
  data() {
    return {
      selectedFile: null,
      avatarUrl: '', // 存储上传后的头像URL
      image: ''
    };
  },
  methods: {
    onFileChange(event) {
      const file = event.target.files[0];
      this.selectedFile = file;
      if (file) {
        // 生成头像的预览URL
        this.avatarUrl = URL.createObjectURL(file);
        this.image = file.name;
      }
    },
    async uploadAvatar() {
      if (!this.selectedFile) return;

      const formData = new FormData();
      // formData.append('image_1', this.selectedFile); 
      formData.append('image', this.image); // Optionally include the file name

      try {
        const response = await UploadAvatar(formData, {
          headers: {
            'Content-Type': 'multipart/form-data',
          },
        });

        // 假设服务器返回上传后的图片URL
        this.avatarUrl = response.data.avatarUrl;
      } catch (error) {
        console.error('上传失败:', error);
      }
    },
    downloadAvatar() {
      if (!this.avatarUrl) return;

      // 创建一个链接元素来触发下载
      const link = document.createElement('a');
      link.href = this.avatarUrl;
      link.download = 'avatar.png'; // 你可以根据需要设置文件名
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    },
  },
};
</script>

<style scoped>
.avatar-upload {
  margin: 0 auto;
  text-align: center;
}

.avatar-preview {
  width: 100px;
  height: 100px;
  border-radius: 50%;
  margin-bottom: 20px;
}

.controls {
  margin-top: 20px;
}

button {
  margin: 5px;
}
</style>
